package csharp.cauth.utils;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author Ярослав (CSharp) Some MD5 functions. Description don't need.
 */
public class MD5
{
	public static byte[] createChecksum(String filename) throws Exception
	{
		InputStream fis = new FileInputStream(filename);

		byte[] buffer = new byte[1024];
		MessageDigest complete = MessageDigest.getInstance("MD5");
		int numRead;
		do
		{
			numRead = fis.read(buffer);
			if (numRead > 0)
			{
				complete.update(buffer, 0, numRead);
			}
		}
		while (numRead != -1);
		fis.close();
		return complete.digest();
	}

	public static String getMD5Checksum(String filename) throws Exception
	{
		byte[] b = createChecksum(filename);
		String result = "";
		for (int i = 0; i < b.length; i++)
		{
			result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
		}
		return result;
	}

	public static String getHash(String str)
	{

		MessageDigest md5;
		StringBuffer hexString = new StringBuffer();

		try
		{

			md5 = MessageDigest.getInstance("md5");

			md5.reset();
			md5.update(str.getBytes());

			byte messageDigest[] = md5.digest();

			for (int i = 0; i < messageDigest.length; i++)
			{
				hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
			}

		}
		catch (NoSuchAlgorithmException e)
		{
			return e.toString();
		}

		return hexString.toString();
	}
}
